package net.sevear.chaos.douban
{
	import avmplus.FLASH10_FLAGS;
	
	import com.adobe.serialization.json.JSON;
	import com.douban.auth.DBAuthenticate;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import net.sevear.chaos.douban.shuo.DBShuoEvent;
	import net.sevear.chaos.douban.shuo.DBShuoFollow;
	import net.sevear.chaos.douban.shuo.DBShuoLike;
	import net.sevear.chaos.douban.shuo.DBShuoMention;
	import net.sevear.chaos.douban.shuo.DBShuoSender;
	import net.sevear.chaos.event.RecommendEvent;
	import net.sevear.chaos.utils.Logger;
	import net.sevear.chaos.view.ChaosLogPanel;
	import net.sevear.chaos.vo.TrackInfo;
	
	public class DBShuoManager extends EventDispatcher
	{
		public static const SHUO_SERVER						:String = "http://shuo.douban.com";
		public static const SHUO_BOOTDATA_URI				:String = "/api/in/bootstrap_data";
		
		public static const OP_BOOT							:int = 0;
		public static const OP_MENTION						:int = 1;
		
		private var loader:URLLoader;
		private var step:int= 0;
		private var isSendingRequest:Boolean;
		private var sender:DBShuoSender;
		private var mentioner:DBShuoMention;
		private var follower:DBShuoFollow;
		private var like:DBShuoLike;
		private var loggin:Boolean;
		public function DBShuoManager(target:IEventDispatcher=null)
		{
			super(target);
			
			//假设登录已经成功
			loggin = true;
			
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,onLoaderComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onIOErrorEvent);
			
			sender = new DBShuoSender();
			sender.addEventListener(DBShuoEvent.SEND_SHARE_FAILED,onShareFaield);
			sender.addEventListener(DBShuoEvent.SEND_SHARE_SUCCESSFULLY,onShare);
			
			mentioner = new DBShuoMention();
			mentioner.addEventListener(RecommendEvent.GET_NEW_RECOMMENDLIST,onGetNewRe);
			
			follower = new DBShuoFollow();
			follower.addEventListener(DBShuoEvent.GET_FOLLOW_LIST,onGetFollowList);
			follower.addEventListener(DBShuoEvent.GET_FOLLOW_LIST_FAILED,onGetFollowListFailed);
		}
		
		private static var instance:DBShuoManager;
		public static function getInstance():DBShuoManager{
			if(instance==null){
				instance = new DBShuoManager();
			}
			return instance;
		}
		
		public function getBootData(force:Boolean = false):void{
			if(loggin == false) return ;
			if(force==true){
				try{
					loader.close();
				}catch(e:Error){
					
				}
			}else if(isSendingRequest){
				return ;
			}
			
			isSendingRequest = true;
			step = OP_BOOT;
			var rst:URLRequest = new URLRequest(SHUO_SERVER+SHUO_BOOTDATA_URI);
			loader.load(rst);
		}
		
		public function recommend(trackInfo:TrackInfo,destUsers:Array=null):void{
			if(sender.recommend(trackInfo,destUsers)==false){
				Logger.getInstance().logInfo("豆瓣说推荐 "+trackInfo.name+" 正忙");
			}
		}
		
		public function getFollowTotal():int{
			return follower.total;
		}
		
		public function getContactList(pageIdx:int):void{
			follower.loadContactList(pageIdx);
		}
		
		public function likeDBShuoRecommend(shuoId:int):void{
			if(like==null){
				like = new DBShuoLike(DBAuthenticate.getInstance().ck);
			}
			like.likeDouBanShuo(shuoId);
		}
		
		private function updateMention(untilTime:Date=null):void{
			mentioner.updateMention();
		}
		
		private function onLoaderComplete(e:Event):void{
			isSendingRequest = false;
			
			try{
				var jsonStr:String = (e.currentTarget as URLLoader).data as String;
				var result:Object = JSON.decode(jsonStr);
			}catch(e:Error){
				
			}
			if(result!=null){
				if(result.msg=="需要登录"){
					loggin = false;
					dispatchEvent(new DBShuoEvent(DBShuoEvent.NEED_LOGIN));
				}else{
					switch (step){
						case OP_BOOT:
							handleBootRst(result);
							break;
					}
				}
			}
		}
		
		private function handleBootRst(result:Object):void{
			var unreadMentions:int = result.stat.unread_mentions_count as int;
			if(follower.total!=result.currentUser.following_count as int){
				follower.total = result.currentUser.following_count as int;
				dispatchEvent(new DBShuoEvent(DBShuoEvent.FOLLOW_TOTAL_UPDATED,
					result.currentUser.following_count as int));
			}
			if(unreadMentions>0){
				updateMention();
			}
		}
		
		private function onShare(e:DBShuoEvent):void{
			ChaosLogPanel.getInstance().addBasicInfo("推荐"+(e.data as TrackInfo).name
				+ " 到豆瓣说成功。");
		}
		
		private function onShareFaield(e:DBShuoEvent):void{
			ChaosLogPanel.getInstance().addBasicInfo("推荐"+(e.data as TrackInfo).name
				+ " 到豆瓣说失败。");
		}
		
		private function onGetNewRe(e:RecommendEvent):void{
			var ev:RecommendEvent = new RecommendEvent(RecommendEvent.GET_NEW_RECOMMENDLIST,e.data);
			dispatchEvent(ev);
		}
		private function onIOErrorEvent(e:IOErrorEvent):void{
			Logger.getInstance().logError("error happened when getting DouBanShuo Bootdata: ",e.text);
		}
		
		private function onGetFollowList(e:DBShuoEvent):void{
			var ev:DBShuoEvent = new DBShuoEvent(DBShuoEvent.GET_FOLLOW_LIST,e.data);
			dispatchEvent(ev);
		}
		
		private function onGetFollowListFailed(e:DBShuoEvent):void{
			Logger.getInstance().logError("获取豆瓣说关注列表出错");
		}
	}
}